package br.com.extrajudicial.controllers;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import br.com.caelum.vraptor.Delete;
import br.com.caelum.vraptor.Get;
import br.com.caelum.vraptor.Path;
import br.com.caelum.vraptor.Put;
import br.com.caelum.vraptor.Resource;
import br.com.caelum.vraptor.Result;
import br.com.extrajudicial.dao.ItemDao;
import br.com.extrajudicial.dao.ItemOrderDao;
import br.com.extrajudicial.models.Item;
import br.com.extrajudicial.models.ItemOrder;

@Resource
public class ItemsOrdersController {
	
	@Autowired ItemOrderDao itemOrderDao;
	@Autowired ItemDao itemDao;
	@Autowired Result result;
	
	@Get @Path("/itemsOrders/{id}/edit")
	public ItemOrder edit(Long id) {
		List<Item> items = this.itemDao.listAll();
		this.result.include("items", items);
		return this.itemOrderDao.load(id);
	}
	
	@Put @Path("/itemsOrders")
	public void update(ItemOrder itemOrder) {
		this.itemOrderDao.update(itemOrder);
		redirectToOrder(itemOrder);
	}
	
	@Delete @Path("/itemsOrders/{id}")
	public void delete(Long id) {
		ItemOrder itemOrder = this.itemOrderDao.load(id);
		this.itemOrderDao.delete(itemOrder);
		redirectToOrder(itemOrder);
	}

	private void redirectToOrder(ItemOrder itemOrder) {
		this.result.redirectTo(OrdersController.class).view(itemOrder.getOrder().getId());
	}

}
